package com.yanqu.road.server.gameplayer.module.activity.gourdplant;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.gourdplant.GourdPlantCombInfo;
import com.yanqu.road.entity.activity.gourdplant.GourdPlantConfig;
import com.yanqu.road.entity.activity.gourdplant.GourdPlantElement;
import com.yanqu.road.entity.activity.gourdplant.GourdPlantUserData;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogGourdPlantWatering;
import com.yanqu.road.entity.player.UserActivityScore;
import com.yanqu.road.logic.bussiness.activity.GourdPlantBussiness;
import com.yanqu.road.pb.activity.GourdPlantProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.gourdplant.GourdPlantMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.pb.GourdPlantPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class GourdPlantModule extends GeneralModule {

    GourdPlantUserData userData;

    public GourdPlantModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        GourdPlantConfig config = GourdPlantMgr.getConfig();
        if (config != null && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            userData = GourdPlantBussiness.getGourdPlantUserData(config.getActivityInfo().getActivityId(), getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                GourdPlantBussiness.addGourdPlantUserData(userData);
            } else if (userData.isUpdateOption()) {
                GourdPlantBussiness.updateGourdPlantUserData(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        syncConfig();
        initUserData();
        syncUserData();
    }


    public GourdPlantUserData getUserData() {
        return userData;
    }

    public void syncConfig() {
        GourdPlantConfig config = GourdPlantMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }

        GourdPlantProto.GourdPlantConfigSyncMsg.Builder builder = GourdPlantPb.parseSyncConfigRespMsg(config, player.getLanguage());
        player.sendPacket(Protocol.U_GOURD_PLANT_SYNC_CONFIG, builder);
    }

    public void initUserData() {
        // 系统未解锁
        if (!SystemOpenMgr.systemOpen(player, eSystemId.GourdPlantActivity.getValue())) {
            return;
        }

        // 没有活动
        GourdPlantConfig config = GourdPlantMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }

        ActivityInfo activityInfo = config.getActivityInfo();

        // 已经有数据了
        if (userData != null && userData.getActivityId() == activityInfo.getActivityId()) {
            return;
        }

        GourdPlantUserData tmpUserData = new GourdPlantUserData();
        tmpUserData.setActivityId(activityInfo.getActivityId());
        tmpUserData.setUserId(getUserId());
        tmpUserData.setScore(0);

        tmpUserData.setInsertOption();
        userData = tmpUserData;
    }

    public void syncUserData() {
        GourdPlantConfig config = GourdPlantMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        GourdPlantUserData data = getUserData();
        if (data == null) {
            return;
        }

        //fix bug 2021.10.1
        //UserActivityScore userActivityScore = player.getModule(ActivityMallModule.class).getUserActivityScore(config.getActivityInfo().getActivityId(), config.getScoreItemId());
        //if(userActivityScore != null && userActivityScore.getTotalScore() > 0) {
        //    player.notifyListener(eGamePlayerEventType.GourdPlantScoreRank.getValue(), userActivityScore.getTotalScore());
        //    player.notifyListener(eGamePlayerEventType.GourdPlantScoreCrossRank.getValue(), userActivityScore.getTotalScore());
        //}

        GourdPlantProto.GourdPlantUserDataSyncMsg.Builder builder = GourdPlantMgr.parseUserDataSyncMsg(data);

        player.sendPacket(Protocol.U_GOURD_PLANT_SYNC_USER_DATA, builder);
    }

    /**
     * 浇水
     */
    public int watering(int type) {
        GourdPlantConfig config = GourdPlantMgr.getConfig();
        int times;
        if(type == 1){
            times = 1;
        }else {
            times = 7;
        }
        int realTimes = times;
        //当前有进度
        if(userData.getCombTimes() > 0 && times == 7){
            realTimes = 7 - userData.getCombTimes();
        }
        //log.debug("user {} realTimes {}", player.getUserId(), realTimes);
        //是否有足够道具
        Property consume = PropertyHelper.parseStringToProperty(config.getUseItemId() + "=" + realTimes);
        //log.debug("user {} consume {}", player.getUserId(), consume.getCountByGoodsId(config.getUseItemId()));
        //道具判定
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(consume)) {
            return GameErrorCode.E_GOURD_PLANT_ACTIVITY_ITEM_NO_ENOUGH;
        }
        //当前组合
        GourdPlantCombInfo combInfo = null;
        //当前组合具体元素
        List<GourdPlantElement> elementList = null;
        //当前组合具体元素（打乱顺序)
        List<Integer> combItems;
        //还没有组合，随机一个
        if(userData.getCombId() == 0){
            combInfo = GourdPlantMgr.randomComb();
            if(combInfo == null){
                return GameErrorCode.E_GOURD_PLANT_ACTIVITY_COMB_ERROR;
            }
            elementList = GourdPlantMgr.getCombSpecialElement(combInfo);
            if(elementList.size() == 0){
                return GameErrorCode.E_GOURD_PLANT_ACTIVITY_COMB_ERROR;
            }
            log.debug("----------------- user {} comb info ------------------------------", player.getUserId());
            log.debug("user {} get comb {}", player.getUserId(), combInfo.getCombId());
            for (GourdPlantElement element : elementList) {
                log.debug(element.getId() + "=" + element.getNum());
            }
        }
        // 扣道具
        if (!player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.GourdPlantActivity, eLogMoneyType.GourdPlantWateringCost)) {
            return GameErrorCode.E_GOURD_PLANT_ACTIVITY_ITEM_NO_ENOUGH;
        }

        if(userData.getCombId() == 0){
            userData.setCombElement(elementList);
            userData.setCombId(combInfo.getCombId());
            //打乱顺序
            userData.setCombItems(GourdPlantMgr.upsetCombItem(elementList));
        }
        combItems = userData.getCombItems();
        //elementList = userData.getCombElement();

        GourdPlantProto.GourdPlantWateringRespMsg.Builder respMsg = GourdPlantProto.GourdPlantWateringRespMsg.newBuilder();
        int combId = 0;
        int totalScore = 0;
        int allTimes = realTimes + userData.getCombTimes();
        int score = realTimes * config.getUserItemScore();
        //总奖励
        Property allReward = new Property();
        totalScore += score;
        //日志
        LogGourdPlantWatering waterLog = new LogGourdPlantWatering(player.getUserId(), config.getActivityInfo().getActivityId(), type);
        //达到组合次数
        if(allTimes == 7){
            //结算
            combInfo = config.getCombInfoMap().get(userData.getCombId());
            combId = userData.getCombId();
            totalScore += combInfo.getIntegral();
            //重置
            userData.setCombId(0);
            userData.setCombTimes(0);
            userData.setCombItems(new ArrayList<>());
            userData.setCombElement(new ArrayList<>());
            //组合奖励
            if(!StringUtils.isNullOrEmpty(combInfo.getRewards())){
                Property property = PropertyHelper.parseStringToProperty(combInfo.getRewards());
                allReward.addProperty(property);
                int lianXin = property.getCountByGoodsId(config.getExchangeItemId()).intValue();
                if(lianXin > 0){
                    userData.setLianXinNum(userData.getLianXinNum() + lianXin);
                    player.notifyListener(eGamePlayerEventType.GourdPlantKeepsakeNum.getValue(), userData.getLianXinNum());
                }
                //组合积分
                int combScore = allReward.getCountByGoodsId(config.getScoreItemId()).intValue();
                waterLog.setCombScore(combScore);
                totalScore += combScore;
            }
            //组合积分
            allReward.addProperty(config.getScoreItemId(), BigInteger.valueOf(combInfo.getIntegral()));
            waterLog.setCombId(combId);
        }else{
            //次数+1
            userData.setCombTimes(realTimes + userData.getCombTimes());
        }
        //每次必获得积分
        player.getModule(CurrencyModule.class).addCurrency(config.getScoreItemId() + "=" + score, eLogMoneyType.GourdPlantActivity, eLogMoneyType.GourdPlantWateringGst);
        waterLog.setScore(score);
        if(!allReward.isNothing()){
            //组合的奖励
            player.getModule(CurrencyModule.class).addCurrency(allReward, eLogMoneyType.GourdPlantActivity, eLogMoneyType.GourdPlantCombRewardGet);
            waterLog.setRewards2(PropertyHelper.parsePropertyToString(allReward));//包含积分
        }
        //每次必获取道具
        if(!StringUtils.isNullOrEmpty(config.getUserItemRewards())){
            Property itemReward = getRandomUseItemReward(config);
            itemReward.rideProperty(realTimes);
            player.getModule(CurrencyModule.class).addCurrency(itemReward, eLogMoneyType.GourdPlantActivity, eLogMoneyType.GourdPlantWateringGst);
            allReward.addProperty(itemReward);
            waterLog.setRewards(PropertyHelper.parsePropertyToString(itemReward));
        }
        allReward.addProperty(config.getScoreItemId(), BigInteger.valueOf(score));
        if(totalScore > 0){
            userData.setScore(userData.getScore() + totalScore);
            player.notifyListener(eGamePlayerEventType.GourdPlantScoreRank.getValue(), userData.getScore());
            player.notifyListener(eGamePlayerEventType.GourdPlantScoreCrossRank.getValue(), userData.getScore());
            //fix bug 2021.10.1 拿获得道具记录来冲榜   userData.getScore()数值已脏
            //UserActivityScore userActivityScore = player.getModule(ActivityMallModule.class).getUserActivityScore(config.getActivityInfo().getActivityId(), config.getScoreItemId());
            //if(userActivityScore != null) {
            //    player.notifyListener(eGamePlayerEventType.GourdPlantScoreRank.getValue(), userActivityScore.getTotalScore());
            //    player.notifyListener(eGamePlayerEventType.GourdPlantScoreCrossRank.getValue(), userActivityScore.getTotalScore());
            //}
        }

        try {
            //日志
            //获得葫芦
            if (combItems.size() > 0) {
                waterLog.setColors(StringUtils.listToString(combItems.subList(allTimes - realTimes, allTimes), ","));
            }
        }catch (Exception e){
            log.error(e);
        }
        LogMgr.addLogGourdPlantWatering(waterLog);

        respMsg.setReward(PropertyHelper.parsePropertyToString(allReward));
        //达到组合
        if(allTimes == 7){
            respMsg.setCombId(combId);
        }
        if(combItems.size() >= allTimes){
            respMsg.addAllCombItem(combItems.subList(0, allTimes));
        }
        respMsg.setRet(0);
        respMsg.setUserData(GourdPlantMgr.getUserDataTempBuilder(userData));
        player.sendPacket(Protocol.U_GOURD_PLANT_WATERING, respMsg);

        return 0;
    }

    private Property getRandomUseItemReward(GourdPlantConfig config) {
        Random random = new Random();
        int idx = RandomHelper.getRandomIndexByWeight(config.getUserItemRewardWeightList(), random);
        return PropertyHelper.parseStringToProperty(config.getUserItemRewardList().get(idx));
    }

}
